//
//  DHHomeCostumeView.m
//  Dresshere
//
//  Created by ZhangPeng on 2018/1/27.
//  Copyright © 2018年 张朋. All rights reserved.
//

#import "DHHomeCostumeView.h"
#import "DHSearchSceneScrollView.h"
#import "DHSearchCategoryScrollView.h"
#import "DHSearchSizeScrollView.h"
#import "DHSearchColorView.h"
#import "DHProductCollectionViewCell.h"
#import "DHProductDetailViewController.h"

@interface DHHomeCostumeView()<DHSearchSceneScrollViewDelegate, DHSearchCategoryScrollViewDelegate, DHSearchColorViewDelegate, UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout, UIScrollViewDelegate>{
    BOOL isFirstLoad;
}

@property (weak, nonatomic) IBOutlet DHSearchSceneScrollView *scenesScrollView;
@property (weak, nonatomic) IBOutlet DHSearchColorView *colorScrollView;
@property (weak, nonatomic) IBOutlet DHSearchCategoryScrollView *categoriesScrollView;
@property (weak, nonatomic) IBOutlet DHSearchSizeScrollView *sizeScrollView;
@property (weak, nonatomic) IBOutlet UIScrollView *contentScorllView;
@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *sizeViewHeightLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *collectionHeightLayout;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *contentViewHeightLayout;

@property (strong, nonatomic) NSMutableArray *dataArray;

@property (strong, nonatomic) NSString *scene_id;
@property (strong, nonatomic) NSString *color_name;
@property (strong, nonatomic) NSString *category_id;
@property (strong, nonatomic) NSString *sex;
@property (strong, nonatomic) NSString *size_name;
@property (assign, nonatomic) NSInteger pageIndex;

@property (assign, nonatomic) BOOL isLoadMore;
@property (assign, nonatomic) BOOL isMoreData;

@end

@implementation DHHomeCostumeView

+ (DHHomeCostumeView *)shareDHHomeCostumeView{
    DHHomeCostumeView *view = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass([DHHomeCostumeView class]) owner:self options:nil] objectAtIndex:0];
    return view;
}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)initView{
    self.scenesScrollView.delegate = self;
    self.categoriesScrollView.delegate = self;
    self.colorScrollView.delegate = self;
    self.sizeViewHeightLayout.constant = 0;
    
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerNib:[UINib nibWithNibName:@"DHProductCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:kDHProductCollectionViewCell];
    self.collectionView.mj_footer = [DHMJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreProductsData)];
    
    addNObserver(@selector(reloadCategory), @"reloadSearchCategory");
    
    self.contentScorllView.delegate = self;
    
    self.isMoreData = YES;
}

- (void)reloadCategory{
    [self.categoriesScrollView loadCategoryData];
    [self loadProductsData];
}

- (void)dealloc
{
    removeNObserver(@"reloadSearchCategory");
}

- (void)loadFilterItems{
    if (!isFirstLoad) {
        [self.categoriesScrollView loadCategoryData];
        [self.scenesScrollView loadSceneData];
        [self.colorScrollView loadColorData];
        isFirstLoad = YES;
    }
}

- (void)loadProductsData{
    self.pageIndex = 0;
    
    self.isMoreData = YES;
    self.isLoadMore = NO;
    
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    [params setObject:@(self.pageIndex) forKey:@"pageIndex"];
    [params setObject:@(20) forKey:@"pageSize"];
    if (self.scene_id) {
        [params setObject:self.scene_id forKey:@"scene_id"];
    }
    if (self.category_id) {
        [params setObject:self.category_id forKey:@"category_id"];
    }
    if (self.size_name) {
        [params setObject:self.size_name forKey:@"size_name"];
    }
    if (self.color_name) {
        [params setObject:self.color_name forKey:@"color_name"];
    }
    if ([GlobalManager shareGlobalManager].user.sex) {
        [params setObject:[GlobalManager shareGlobalManager].user.sex forKey:@"sex"];
    }
    
    [[DHNetAPIClient shareDHNetAPIClient] request_search_productsWithDictionary:params andBlock:^(id data, NSError *error) {
        [self.dataArray removeAllObjects];
        [self.dataArray addObjectsFromArray:[data objectForKey:@"products"]];
        [self.collectionView reloadData];
        
        if (self.dataArray.count % 2 > 0) {
            self.collectionHeightLayout.constant = (self.dataArray.count / 2) * 317 + 317 + (self.pageIndex+1)*20 + 40;
        }else{
            self.collectionHeightLayout.constant = (self.dataArray.count / 2) * 317 + (self.pageIndex+1)*20 + 40;
        }
        self.contentScorllView.contentSize = CGSizeMake(kScreenWidth, 54 * 4 + self.collectionHeightLayout.constant);
        self.contentViewHeightLayout.constant = self.contentScorllView.contentSize.height;
        
        if (self.dataArray.count < 20) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            self.isMoreData = NO;
        }else{
            [self.collectionView.mj_footer endRefreshing];
        }
        self.pageIndex += 1;
    }];
}

- (void)loadMoreProductsData{
    NSMutableDictionary *params =[NSMutableDictionary dictionary];
    [params setObject:@(self.pageIndex) forKey:@"pageIndex"];
    [params setObject:@(20) forKey:@"pageSize"];
    if (self.scene_id) {
        [params setObject:self.scene_id forKey:@"scene_id"];
    }
    if (self.category_id) {
        [params setObject:self.category_id forKey:@"category_id"];
    }
    if (self.size_name) {
        [params setObject:self.size_name forKey:@"size_name"];
    }
    if (self.color_name) {
        [params setObject:self.color_name forKey:@"color_name"];
    }
    if ([GlobalManager shareGlobalManager].user.sex) {
        [params setObject:[GlobalManager shareGlobalManager].user.sex forKey:@"sex"];
    }
    
    [[DHNetAPIClient shareDHNetAPIClient] request_search_productsWithDictionary:params andBlock:^(id data, NSError *error) {
        
        NSArray *arr = [data objectForKey:@"products"];
        [self.dataArray addObjectsFromArray:arr];
        [self.collectionView reloadData];
        
        if (self.dataArray.count % 2 > 0) {
            self.collectionHeightLayout.constant = (self.dataArray.count / 2) * 317 + 317 + (self.pageIndex+1)*20 + 40;
        }else{
            self.collectionHeightLayout.constant = (self.dataArray.count / 2) * 317 + (self.pageIndex+1)*20 + 40;
        }
        self.contentScorllView.contentSize = CGSizeMake(kScreenWidth, 54 * 4 + self.collectionHeightLayout.constant);
        self.contentViewHeightLayout.constant = self.contentScorllView.contentSize.height;
        
        if (arr.count < 20) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            self.isMoreData = NO;
        }else{
            [self.collectionView.mj_footer endRefreshing];
        }
        self.pageIndex += 1;
        self.isLoadMore = NO;
    }];
}

#pragma mark - DHSearchSceneScrollViewDelegate
- (void)searchSceneScrollViewSelected:(NSString *)scene_id{
    self.scene_id = scene_id;
    [self loadProductsData];
}

#pragma mark - DHSearchColorViewDelegate
- (void)searchColorViewDelegateSelected:(NSString *)color_name{
    self.color_name = color_name;
    [self loadProductsData];
}

#pragma mark - DHSearchCategoryScrollViewDelegate
- (void)searchCategoryScrollViewSelected:(NSString *)category_id{
    self.category_id = category_id;
    if (self.category_id) {
        [self.sizeScrollView loadSizeWithCatrgoryID:self.category_id];
        self.sizeViewHeightLayout.constant = 54;
    }else{
        [self.sizeScrollView.sizesArr removeAllObjects];
        self.sizeViewHeightLayout.constant = 0;
        [self.sizeScrollView updateSizesView];
    }
    [self loadProductsData];
}

#pragma mark - UICollectionViewDataSource and UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DHProductCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kDHProductCollectionViewCell forIndexPath:indexPath];
    Product *product = [Product modelWithDictionary:self.dataArray[indexPath.row]];
    [cell updateWithProduct:product];
    return cell;
}

#pragma mark ---- UICollectionViewDelegateFlowLayout
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return (CGSize){kScreenWidth/2,317};
}

// 两行之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 3;
}

// 两个cell之间的最小间距，是由API自动计算的，只有当间距小于该值时，cell会进行换行
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 0;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    Product *product = [Product modelWithDictionary:self.dataArray[indexPath.row]];
    DHProductDetailViewController *detailController = [[DHProductDetailViewController alloc] initWithProductID:product._id brandName:product.brand.name];
    [self.viewController.navigationController pushViewController:detailController animated:YES];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView.contentSize.height - scrollView.contentOffset.y < kScreenHeight) {
        if (!self.isLoadMore && self.isMoreData) {
            [self loadMoreProductsData];
            self.isLoadMore = YES;
        }
    }
}

@end
